/** 缓存模块 */
/**
 * @name: setCookie
 * @cname: 存储cookie	
 * @desc: 存储一个cookie至浏览器
 * @param {*} key val expires
 * @panme: key=a val=1 expires=2
 * @result: storage里面出现key为a value为1 size为2的缓存
*/
export function setCookie(key, val, expires) {
	if (typeof val === 'object')
		val = JSON.stringify(val)
	let now = new Date()
	now.setMinutes(now.getMinutes() + expires)
	document.cookie = `${key}=${encodeURI(val)};expires=${now.toUTCString()}`
}

/**
 * @name: removeCookie
 * @cname: 删除cookie
 * @desc: 删除对应key值得cookie
 * @param {*} key 
 * @panme: key=a
 * @result: setCookie存储的cookie a被删除
*/
export function removeCookie(key) {
	this.setCookie(key, null, -1)
}

/**
 * @name: getCookie
 * @cname: 获取cookie
 * @desc: 根据key获取cookie的值，如果不传key则获取全部cookie
 * @param {*} key 
 * @panme: key为空
 * @result: {BIDUPSID: 'A33974C282EA89BA9F5C6F58224FB45A', PSTM: '1641537127', BAIDUID: 'A33974C282EA89BA9743626AE3884AE7:FG', BD_UPN: '12314753', BAIDUID_BFESS: 'A33974C282EA89BA9743626AE3884AE7:FG', …}
*/
export function getCookie(key) {
	let obj = {}
	document.cookie.split('; ').forEach(r => {
		let kv = r.split('=')
		obj[kv[0]] = decodeURI(kv[1])
	})
	if (key) {
		let res = null
		try {
			res = JSON.parse(obj[key])
		} catch (error) {
			res = obj[key]
		}
		return res
	}
	return obj
}